package com.xxx.Dao;

import com.xxx.pojo.Cla;
import com.xxx.util.DbUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @version v1.0
 * @Description
 * @Author admin
 * @date 2021/7/29  14:18
 * @Copyright
 */
public class claDoaimpl implements claDao {

    @Override
    public int insert(ArrayList<Cla> list) {
        String sql = "insert into cla(name,num,createdate)values (?,?,?)";
        try (Connection connection = DbUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)
        ) {
            int i = 0;
            Iterator<Cla> iterator = list.iterator();
            while (iterator.hasNext()) {
                Cla cla = iterator.next();
                preparedStatement.setString(1, cla.getName());
                preparedStatement.setInt(2, cla.getNum());
                preparedStatement.setString(3, cla.getCreateDate());
                i = preparedStatement.executeUpdate();
            }
            return i;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int delete(int claId) {
        return 0;
    }

    @Override
    public int update(Cla cla) {
        return 0;
    }

    @Override
    public ArrayList<Cla> query() {
        return null;
    }

    @Override
    public int transaction(Connection connection, ArrayList<Cla> list) {
        String sql = "insert into cla(name,num,createdate)values (?,?,?)";
        String querySql = "select LAST_INSERT_ID()";

        try (
                PreparedStatement preparedStatement1 = connection.prepareStatement(sql);
                PreparedStatement preparedStatement2 = connection.prepareStatement(querySql);
        ) {
            Iterator<Cla> iterator = list.iterator();
            int claid = 0;
            while (iterator.hasNext()) {
                Cla cla1 = iterator.next();
                preparedStatement1.setString(1, cla1.getName());
                preparedStatement1.setInt(2, cla1.getNum());
                preparedStatement1.setString(3, cla1.getCreateDate());
                preparedStatement1.executeUpdate();
                ResultSet resultSet = preparedStatement2.executeQuery();
                while (resultSet.next()) {
                    claid = resultSet.getInt(1);
                }
                return claid;
            }
        } catch (SQLException throwables) {
            throw new RuntimeException("班级异常");
        }
        return 0;
    }
}
